package com.pig4cloud.pigx.common.security.resource.component;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.client.RestTemplate;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/8/5 15:43
 **/
@ComponentScan("com.pig4cloud.pigx.common.security")
public class PigxResourceServerAutoConfiguration implements ApplicationContextAware {

    /**
     * redis工厂，默认使用 lettue
     */
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    private ApplicationContext applicationContext;

    /**
     * 负载均衡的RestTemplate:加上@LoadBalanced
     *
     * @return
     */
    @Bean
    @Primary
//    @LoadBalanced
    public RestTemplate lbRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.setInterceptors(new ArrayList<>(beansOfType.values())); 设置ClientHttpRequestInterceptor监听器
//        restTemplate.setErrorHandler(new RestResponseErrorHandler()); 设置异常处理
        return restTemplate;
    }

    @Bean
    public TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        //设置redis中token存储中的前缀
        redisTokenStore.setPrefix("auth-token:");
        return redisTokenStore;
    }

    /**
     * 可以通过配置文件中security:oauth2:resource:设置RemoteTokenServices需要的相关参数
     *
     * @return
     */
//    @Bean
//    public RemoteTokenServices remoteTokenServices() {
//        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
//        // 设置授权服务器check_token端点完整地址
//        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:3333/oauth/check_token");
//        // 设置客户端id与secret，注意：client_secret值不能使用passwordEncoder加密！
//        remoteTokenServices.setClientId("client_1");
//        remoteTokenServices.setClientSecret("client_1_secret");
//        return remoteTokenServices;
//    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
